using System;
using System.IO;
using System.Text.Json;
using Avalonia;

namespace Launcher;

public class Setting
{
    public struct SettingRect
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }

        public static implicit operator PixelRect(SettingRect rect)
        {
            return new PixelRect(new PixelPoint(rect.X, rect.Y), new PixelSize(rect.Width, rect.Height));
        }

        public static implicit operator SettingRect(PixelRect rect)
        {
            return new SettingRect { X = rect.X, Y = rect.Y, Width = rect.Width, Height = rect.Height };
        }
    }

    public static Setting Instance { get; private set; } = new();
    public string CachePath { get; set; } = string.Empty;
    public SettingRect? WindowRect { get; set; }
    public bool UseMultiThreadedDownloading { get; set; }

    public static void Load()
    {
        string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        string settingPath = Path.Combine(appDataPath, "DesktopGameLauncher", "setting.json");

        Setting? setting = null;
        try
        {
            if (File.Exists(settingPath))
            {
                setting = JsonSerializer.Deserialize<Setting>(File.ReadAllText(settingPath));
            }
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e);
        }
        
        Instance = setting ?? new();
        Instance.SetDefault();
    }

    public static void Save()
    {
        string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        var settingDirectory = Path.Combine(appDataPath, "DesktopGameLauncher");
        string settingPath = Path.Combine(settingDirectory, "setting.json");
        try
        {
            if (!Directory.Exists(settingDirectory))
            {
                Directory.CreateDirectory(settingDirectory);
            }
            File.WriteAllText(settingPath,JsonSerializer.Serialize(Instance));
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e);
        }
    }

    private void SetDefault()
    {
        bool changed = false;

        if (string.IsNullOrWhiteSpace(CachePath))
        {
            CachePath = AppConfig.Instance.DefaultCachePath;
            changed = true;
        }

        if (changed)
        {
            Save();
        }
    }
}